package ws

import (
	"itodo/core/localwrap"
	"itodo/ws/tasks"
	"net/http"
	"path/filepath"
	"strconv"

	"github.com/RocksonZeta/hubx"
)

type User struct{}

var log = localwrap.GetLogger().Fork("combat/ws", "")

func serveHome(w http.ResponseWriter, r *http.Request) {
	log.Trace().Str("url", r.URL.String()).Send()
	if r.URL.Path != "/" {
		http.Error(w, "Not found", http.StatusNotFound)
		return
	}
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	http.ServeFile(w, r, "play.html")
}

func GetUserByToken(token string) User {
	return User{}
}

func serveGameWs(w http.ResponseWriter, r *http.Request) {
	log.Trace().Func("serveGameWs").Str("url", r.URL.String()).Send()
	id, err := strconv.Atoi(filepath.Base(r.URL.Path))
	if err != nil {
		w.WriteHeader(400)
		w.Write([]byte("game's id should be an integer."))
		return
	}
	actor, err := tasks.GetOrNewTaskCenter(id)
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte("create game failed"))
		return
	}
	token := r.URL.Query().Get("token")
	user := GetUserByToken(token)
	// check user
	hubx.ServeWs(actor.Hub(), w, r, hubx.DefaultUpgrader(), map[string]interface{}{tasks.PropUser: user})
}
func Start(listen string) {
	log.Info().Func("Start").Str("listen", listen).Send()
	http.HandleFunc("/", serveHome)
	http.HandleFunc("/hubx/game/", serveGameWs)
	err := http.ListenAndServe(listen, nil)
	if err != nil {
		log.Error().Stack().Err(err).Msg(err.Error())
	}
}
